#include "ByteBufferPool.h"
#include "ByteBuffer.h"

namespace cm_base
{
    ByteBufferPool::ByteBufferPool():m_total(0)
    {
    }

    ByteBufferPool::~ByteBufferPool()
    {
        teardown();
    }

    bool ByteBufferPool::setup(UInt32 poolSize, size_t bufferLen)
    {
        ByteBuffer* p = NULL;
        for( int i=0; i<poolSize; i++)
        {
            p = new ByteBuffer(bufferLen);
            if(p){
                p->setParent(this);
                m_queue.enqueueNotification(p);
                m_total++;
            }else{
                return false;
            }
        }
        return true;
    }

    bool ByteBufferPool::teardown()
    {
        UInt32 i = 0;
        ByteBuffer* p=NULL;

        while( p=get(0) ){
            p->decreaseRef();
            i++;
        }

        if( i != m_total ){
            return false;
        }
        return true;
    }

    void ByteBufferPool::put(ByteBuffer* pb)
    {
        m_queue.enqueueNotification(pb);
    }

    ByteBuffer* ByteBufferPool::get()
    {
        return (ByteBuffer*)m_queue.waitDequeueNotification();
    }

    ByteBuffer* ByteBufferPool::get(long ms)
    {
        return (ByteBuffer*)m_queue.waitDequeueNotification(ms);
    }

    int ByteBufferPool::getInPoolCount()
    {
        return m_queue.size();
    }

}